﻿using HandyControl.Controls;
using SqlSugar;
using System;

using System.IO;
using System.Xml.Linq;

namespace Infov1.Models
{
    public class DbContext
    {
        private const string ConnectionString =
    "Data Source=149.88.87.121,5021;Initial Catalog=kjglq;User ID=info;Password=changAN626;TrustServerCertificate=True;MultipleActiveResultSets=true";

        //获取配置文件
        private static string GetConnectionString()
        {
            const string configPath = "Appaction.xml";
            try
            {
                if (!File.Exists(configPath))
                {
                    Growl.Warning("请先配置数据库连接信息！");
                    return null;
                }

                var doc = XDocument.Load(configPath);
                var serverAddress = doc.Root?.Element("link")?.Value;

                if (string.IsNullOrWhiteSpace(serverAddress))
                {
                    Growl.Warning("请先配置数据库连接信息！");
                    return null;
                }

                return $"Data Source={serverAddress};Initial Catalog=kjglq;User ID=info;Password=changAN626;TrustServerCertificate=True;";
            }
            catch (Exception ex)
            {
                Growl.Error($"读取配置文件失败：{ex.Message}");
                return null;
            }
        }
        //数据库连接
        public static SqlSugarClient GetConnection()
        {
            try
            {
                var connectionString = GetConnectionString();
                if (connectionString == null)
                {
                    return null;
                }

                var db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = connectionString,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute,
                    MoreSettings = new ConnMoreSettings
                    {
                        IsAutoRemoveDataCache = true
                    }
                });

                // 测试连接
                db.Open();
                return db;
            }
            catch (Exception ex)
            {
                Growl.Error($"数据库连接失败：{ex.Message}");
                return null;
            }
        }
        // 使用示例方法
        public static void TestConnection()
        {
            using (var db = GetConnection())
            {
                if (db != null)
                {
                    Growl.SuccessGlobal("数据库连接成功！");
                }
            }
        }
    }
}